package util

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

// AuthMiddleware 验证 JWT Token 的中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取 Authorization 字段
		authorizationHeader := c.GetHeader("Authorization")
		if authorizationHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Missing token"})
			c.Abort()
			return
		}

		// 解析并验证 Token
		claims, err := VerifyToken(authorizationHeader)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			c.Abort()
			return
		}

		// 将解析的用户 ID 存入 Gin 的 Context 中，以便后续处理函数使用
		c.Set("user_id", claims.UserId)
		log.Printf("AuthMiddleware中间件设置了user_id：%v", claims.UserId)
		c.Next()
	}
}

// GetUserIDFromContext 从 Gin 的 Context 中获取用户 ID
func GetUserIDFromContext(c *gin.Context) string {
	userId, _ := c.Get("user_id")
	if userIdInt, ok := userId.(int64); ok {
		return strconv.FormatInt(userIdInt, 10)
	}
	return "0"
}
